package com.qlmy.cn.api

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody

class ConvertInterceptor : Interceptor {
    companion object {
        const val CONTENT_TYPE_KEY = "Api-Type"
        const val JSON_CONTENT_TYPE_VALUE = "JSON"
        const val JSON_CONTENT_TYPE_HEADER = "$CONTENT_TYPE_KEY:$JSON_CONTENT_TYPE_VALUE"
        const val JSON_CONTENT_TYPE = "Content-Type:application/json;charset=utf-8"
        const val PARAM = "PARAM"
        private val CONTENT_TYPE = "application/json;charset=utf-8".toMediaType()
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val contentType = request.header(CONTENT_TYPE_KEY)
        if (JSON_CONTENT_TYPE_VALUE == contentType && "POST" == request.method) {
            val formBody = request.body as? FormBody
            if (formBody != null) {
                try {
                    val params = JSONObject()
                    for (i in 0 until formBody.size) {
                        if (formBody.name(i) != PARAM)
                            params[formBody.name(i)] = formBody.value(i)
                    }
                    request = request.newBuilder()
                            .removeHeader(CONTENT_TYPE_KEY)
                            .post(params.toJSONString().toRequestBody(CONTENT_TYPE))
                            .build()
                } catch (e: Throwable) {
                    throw InterceptorException("okhttp拦截器出异常")
                }
            }
        }
        val response = chain.proceed(request)
        try {// 把null过滤掉
            return response.newBuilder().body(JSON.parseObject(response.body?.string()).toJSONString().toResponseBody(
                CONTENT_TYPE
            )).build()
        } catch (e: Exception) {
            return response.newBuilder().body("""{"success":false,"msg":"系统出现异常"}""".toResponseBody(
                CONTENT_TYPE
            )).build()
        }
    }
}